package other.model02;

import java.util.HashMap;

/**
 * @ClassName: BeanFactory
 * @Description: 单例注册表
 * @Version: v1.0.0
 * @Author: tang
 * @Date: 2022/06/06
 * Modification History:
 * Date             Author      Version     Description
 * -------------------------------------------------------------
 * 2022/06/06      tang        v1.0.0      创建
 */
public class BeanFactory {
	/**
	 * 此处用饿汉式单例实现模式，重点是维护此注册表
	 *  */
	private BeanFactory(){}
	private static BeanFactory beanFactory = new BeanFactory();
	public static BeanFactory getInstance(){
		return beanFactory;
	}
	
	//缓存单例对象的hash表
	private final HashMap<String, Object> creatMap = new HashMap<>();
	
	//通过类名获取其单例对象
	public Object getBean(String className){
		Object bean = creatMap.get(className);
		//使用双重检测锁来实现单例
		if(bean == null){
			synchronized(creatMap){
				bean = creatMap.get(className);
				if (bean == null){
					try {
						bean =  Class.forName(className).newInstance();
					} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
						e.printStackTrace();
					}
					creatMap.put(className, bean);
				}
			}
		}
		return bean;
	}
}
